package cn.zbacm.api.user.service;

import cn.zbacm.api.user.entity.User;
import cn.zbacm.api.user.entity.UserSession;
import cn.zbacm.api.user.repository.UserSessionRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class UserSessionService {
  @Autowired
  private UserSessionRepository userSessionRepository;

  @Transactional(rollbackFor = Exception.class)
  public void keep(User user, String token) {
    log.info("start to keep user new session");
    List<UserSession> userSessions = userSessionRepository.findByUserAndIsDisabledFalse(user);
    for (UserSession session : userSessions) {
      session.setIsDisabled(true);
    }
    userSessionRepository.saveAll(userSessions);
    log.info("kick off {} previous sessions", userSessions.size());

    UserSession session = UserSession.builder().user(user).token(token).isDisabled(false).build();
    userSessionRepository.save(session);
    log.info("new session created successfully");
  }
}
